<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With,X-Access-Token');
header('Access-Control-Expose-Headers: Content-Length, Content-Range');
header('Access-Control-Max-Age: 86400');  // 预检请求缓存24小时

// 处理OPTIONS预检请求（需在路由解析前完成）
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(204);
    exit();
}
try {
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);
// 加载配置文件
require_once __DIR__ . '/inc/config.php';


// 自动加载类
spl_autoload_register(function ($className) {
    $file = __DIR__ . '/classes/' . $className . '.class.php';
    if (file_exists($file)) {
        require_once $file;
    }
});
$auth = new Auth($conn);
$dependencies = [
    PDO::class => $conn,
    Auth::class => $auth
];

    $route = $_GET['r'] ?? '';
    $routeParts = explode('/', trim($route, '/'));
    $className = !empty($routeParts[0]) ? ucfirst($routeParts[0]) : 'Index';
    $methodName = $routeParts[1] ?? 'index';
    $classFile = __DIR__ . '/classes/' . $className . '.class.php';

    if (!file_exists($classFile)) {
        throw new Exception("路由不存在", 404);
    }

    require_once $classFile;
    $reflector = new ReflectionClass($className);

    // 自动解析构造函数参数
    $constructorParams = [];
    if ($reflector->hasMethod('__construct')) {
        $constructor = $reflector->getMethod('__construct');
        foreach ($constructor->getParameters() as $param) {
            $type = $param->getType();
            if ($type && !$type->isBuiltin()) {
                $className = $type->getName();
                $constructorParams[] = $dependencies[$className] 
                    ?? new $className(...($dependencies)); // 递归解析
            }
        }
    }

    $instance = $reflector->newInstanceArgs($constructorParams);
    
    if (!$reflector->hasMethod($methodName)) {
        throw new Exception("方法 {$methodName} 不存在", 404);
    }

    // 解析方法参数
    $method = $reflector->getMethod($methodName);
    $methodParams = [];
    foreach ($method->getParameters() as $param) {
        $type = $param->getType();
        if ($type && !$type->isBuiltin()) {
            $className = $type->getName();
            if (isset($dependencies[$className])) {
                $methodParams[] = $dependencies[$className];
            } else if ($param->isOptional()) {
                $methodParams[] = $param->getDefaultValue();
            }
        }
    }

    $instance->$methodName(...$methodParams);

} catch (Throwable $e) {
    while (ob_get_level() > 0) ob_end_clean();
    $statusCode = is_numeric($e->getCode()) ? (int)$e->getCode() : 500;
    // http_response_code($statusCode);
    // header('Content-Type: application/json; charset=utf-8', true);
    echo json_encode([
        'code' => $statusCode,
        'msg' => $e->getMessage(),
        // 开发环境可添加调试信息
        // 'debug' => ['file' => $e->getFile(), 'line' => $e->getLine()]
    ]);
    exit;
}